const Koa = require("koa");
const session = require("koa-session");

const app = new Koa();

// 配置 session
app.keys = ["$%@#$#@$sdfdsfdsdjhriuejlk颠倒是非211125465357865"];

const CONFIG = {
  key: "koa.sess",
  maxAge: 86400000, // 过期时间，单位 ms
  autoCommit: true, // 自动提交 session
  overwrite: true, // 可以被覆盖
  httpOnly: true, // 仅服务器可访问
  signed: true, // 需要签名
  rolling: false, // 每次请求重新设置过期时间
  renew: false, // 访问快过期时自动续期
};
app.use(session(CONFIG, app));

app.use(async (ctx, next) => {
  if (ctx.path === "/set_cookie") {
    ctx.cookies.set("name", Math.random().toString(36).substring(7));
    ctx.session.age = Math.random().toString(36).substring(7);
    ctx.body = "设置了cookie和session";
  } else if (ctx.path === "/cookie") {
    let name = ctx.cookies.get("name");
    let age = ctx.session.age;
    ctx.body = [name, age];
  } else {
    await next();
  }
});

app.listen(3000, () => console.log("Server running on http://localhost:3000"));
